package com.zone.vehicle.superapp.view.appmanager.tab;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zone.lib.download.db.entity.Download;
import com.zone.lib.download.enums.AppStatusEnum;
import com.zone.sdk.common.http.base.Result;
import com.zone.vehicle.lib.view.utils.ImageUtil;
import com.zone.vehicle.lib.view.widget.CustomDialog;
import com.zone.vehicle.superapp.R;
import com.zone.vehicle.superapp.bean.AppBean;
import com.zone.lib.download.enums.AppTypeEnum;
import com.zone.vehicle.superapp.databinding.FragmentAppManagerLightBinding;
import com.zone.vehicle.superapp.databinding.FragmentAppManagerLightItemBinding;
import com.zone.vehicle.superapp.model.AppManagerViewModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;
import com.zone.vehicle.superapp.view.common.base.BaseFragment;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * A fragment representing a list of Items.
 */
public class LightAppListFragment extends BaseFragment {

    private FragmentAppManagerLightBinding binding;

    private LightAppAdapter lightAppAdapter;

    private static AppManagerViewModel viewModel;

    private static Activity activity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = requireActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentAppManagerLightBinding.inflate(inflater);
        viewModel = new ViewModelProvider(requireActivity(), new ViewModelFactory()).get(AppManagerViewModel.class);
        initView();
        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    private void initView(){
        lightAppAdapter = new LightAppAdapter(new ArrayList<>());
        binding.lightList.setAdapter(lightAppAdapter);
        binding.lightList.setLayoutManager(new GridLayoutManager(getContext(), 1));
        viewModel.getError().observe(getViewLifecycleOwner(), new Observer<Result>() {
            @Override
            public void onChanged(Result result) {
                if (ObjectUtils.isNotEmpty(result) && StringUtils.isNotEmpty(result.getResultMsg())) {
                    showLoginFailed(result.getResultCode() + result.getResultMsg());
                }
            }
        });
        viewModel.getActivityLightApp().observe(getViewLifecycleOwner(), new Observer<List<AppBean>>() {
            @Override
            public void onChanged(List<AppBean> appEntities) {
                lightAppAdapter.setData(appEntities);
                lightAppAdapter.notifyDataSetChanged();
            }
        });

        setHandler(handler);
    }

    private void initData(){
        viewModel.getActivityApp(activity, AppTypeEnum.APP_LIGHT);
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {

            switch (msg.what){
                case 1:
                    Download download = (Download)msg.obj;
                    if (ObjectUtils.isNotEmpty(download) && download.getAppType().equals(AppTypeEnum.APP_LIGHT.getName())){
                        initData();
                    }
            }
            return false;
        }
    });

    private static class LightAppAdapter extends RecyclerView.Adapter<LightAppAdapter.ViewHolder>{

        private List<AppBean> data;

        private FragmentAppManagerLightItemBinding binding;

        public LightAppAdapter(List<AppBean> data) {
            this.data = data;
        }

        public void setData(List<AppBean> data) {
            this.data = data;
        }

        @NotNull
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            binding = FragmentAppManagerLightItemBinding.inflate(LayoutInflater.from(parent.getContext()));
            return new ViewHolder(binding.getRoot());
        }

        @Override
        public void onBindViewHolder(@NotNull ViewHolder holder, int position) {
            if (ObjectUtils.isEmpty(data)){
                return;
            }
            AppBean appBean = data.get(position);
            Download download = appBean.getDownload();
            holder.name.setText(appBean.getName());
            holder.actions.setVisibility(View.GONE);
//            String timeString = TimeUtils.getRecentTimeSpanByNow(DateUtils.getStringToLong(appBean.getDownload().getCreateTime()));
//            holder.time.setText(StringUtils.isNotBlank(timeString)?timeString:appBean.getDownload().getCreateTime());
//            //设置图片大小
//            RoundedCorners roundedCorners = new RoundedCorners(50);
//            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners)
//                    .placeholder(new ColorDrawable(Color.GRAY))//设置占位图
////                    .error(R.mipmap.logo_app)//设置异常图片
//                    .override(300, 300);//降低内存消耗
//            Glide.with(holder.itemView.getContext())
//                    .asBitmap()
//                    .load(appBean.getIcon())
//                    .apply(options)
//                    .into(holder.icon);
            ImageUtil.load(holder.itemView.getContext(), holder.icon, appBean.getIconUrl());
            holder.actions.setVisibility(View.GONE);
            holder.oneWord.setText(download.getOneWord());
            if (appBean.getDownCount() > 10000){
                holder.useCount.setText("1w+ 人使用");
            }else {
                holder.useCount.setText(appBean.getDownloadCount()+" 人使用");
            }

            AppStatusEnum appStatusEnum = AppStatusEnum.get(download.getDownloadStatus());
            if (ObjectUtils.isNotEmpty(appStatusEnum)) {
                if (appStatusEnum == AppStatusEnum.DOWNLOAD_PREPARE){
                    holder.btn_activity.setText("loading");
                }else {
                    holder.btn_activity.setText(appStatusEnum.TITLE);
                }
            } else {
                holder.btn_activity.setText(AppStatusEnum.DOWNLOAD_DEFAULT_LIGHT.TITLE);
            }
            holder.btn_activity.setTag(position);
            holder.btn_activity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int p = (int) v.getTag();
                    AppBean b = data.get(p);
                    if (null == b) {
                        Log.e(TAG, "error click of null data");
                        return;
                    }
                    Download d = b.getDownload();
                    if (null == d || AppStatusEnum.get(d.getDownloadStatus()) == null) {
                        Log.e(TAG, "error click download of null download data");
                        return;
                    }
                    switch (AppStatusEnum.get(d.getDownloadStatus())) {
                        case LIGHT_INSTALL_COMPLETE:
                            viewModel.startApp(activity, b);
                            break;
                        case LIGHT_INSTALL_FAIL:
                        case INSTALL_FAIL:
                            viewModel.downLoadApp(activity, AppStatusEnum.DOWNLOAD_PREPARE, b);
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    binding.btnActivity.setText(AppStatusEnum.DOWNLOAD_PREPARE.TITLE);
                                }
                            });
                            break;
                    }
                }
            });
            holder.more.setTag(holder.actions);
            holder.more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Object a = v.getTag();
                    if (null == a){
                        Log.e(TAG, "error more of null tag data light ");
                        return;
                    }
                    LinearLayout actions = (LinearLayout) a;
                    actions.setVisibility(View.VISIBLE);
                }
            });
            holder.item.setTag(holder.actions);
            holder.item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Object a = v.getTag();
                    if (null == a){
                        Log.e(TAG, "error item of null tag data light ");
                        return;
                    }
                    LinearLayout actions = (LinearLayout) a;
                    actions.setVisibility(View.GONE);
                }
            });
            holder.delete.setTag(position);
            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int p = (int) v.getTag();
                    AppBean b = data.get(p);
                    if (null == b) {
                        Log.e(TAG, "error click of null data light");
                        return;
                    }
                    showDialog(activity, b);
                }
            });
        }

        private void showDialog(Context context, AppBean appBean){
            CustomDialog dialog = new CustomDialog(context);
            dialog.setTitle("是否确认删除快应用");
            dialog.setSubTitle(appBean.getName());
            dialog.setPositive("确认");
            dialog.setNegtive("取消");
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog.cancel();
                }
            });
            dialog.setOnClickBottomListener(new CustomDialog.OnClickBottomListener() {
                @Override
                public void onPositiveClick() {
                    dialog.cancel();
                    viewModel.delete(context, appBean);
                }

                @Override
                public void onNegtiveClick() {
                    dialog.cancel();
                }
            });
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.show();
                }
            });
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {

            private final View item;
            private final ImageView icon;
            private final TextView name;
            private final TextView oneWord;
            private final TextView useCount;
            private final AppCompatButton btn_activity;
            private final AppCompatTextView more;
            private final LinearLayout actions;
            private final AppCompatTextView delete;

            public ViewHolder(View itemView) {
                super(itemView);
                item = itemView.findViewById(R.id.item);
                icon = itemView.findViewById(R.id.icon);
                name = itemView.findViewById(R.id.name);
                oneWord = itemView.findViewById(R.id.oneWord);
                useCount = itemView.findViewById(R.id.useCount);
                btn_activity = itemView.findViewById(R.id.btn_activity);
                more = itemView.findViewById(R.id.more);
                actions = itemView.findViewById(R.id.actions);
                delete = itemView.findViewById(R.id.delete);
            }
        }
    }

}